<template>
  <div>
    <el-table :data="posts">
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="content" label="内容"></el-table-column>
      <el-table-column prop="authorUsername" label="作者"></el-table-column>
      <el-table-column prop="createdAt" label="发布时间" :formatter="formatDate"></el-table-column>
      <el-table-column prop="tags" label="标签" :formatter="formatTags"></el-table-column>
      <el-table-column prop="category.name" label="分类"></el-table-column>
      <el-table-column prop="resourceFileName" label="资源文件名"></el-table-column>
      <el-table-column prop="resourceDescription" label="资源描述"></el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import axios from '../plugins/axios'

interface Post {
  id: number;
  title: string;
  content: string;
  authorId: number;
  authorUsername: string;
  resourceId: number | null;
  resourceFileName: string | null;
  resourceDescription: string | null;
  createdAt: string;
  tags: string[];
  category: {
    id: number;
    name: string;
    parentId: number | null;
    createdAt: string;
    updatedAt: string;
    postIds: number[];
  };
}

const posts = ref<Post[]>([])

const fetchPosts = async () => {
  try {
    const response = await axios.get('/posts')
    posts.value = response.data
  } catch (error) {
    console.error('Failed to fetch posts:', error)
  }
}

// 日期格式化函数
const formatDate = (row: any, column: any, cellValue: string) => {
  const date = new Date(cellValue)
  const options: Intl.DateTimeFormatOptions = {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  }
  return date.toLocaleDateString('zh-CN', options)
}

// 标签格式化函数
const formatTags = (row: any, column: any, tags: string[]) => {
  return tags.join(', ')
}

onMounted(() => {
  fetchPosts()
})
</script>

<style scoped>
.el-table {
  width: 100%;
}
</style>